package com.yn.xr.middleware.user.rmi.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.yn.xr.common.exception.UserLoginException;
import com.yn.xr.common.exception.base.BaseException;
import com.yn.xr.middleware.user.rmi.UserRegisterRmiService;
import com.yn.xr.middleware.user.service.UserLoginLogService;
import com.yn.xr.middleware.user.service.UserRegisterService;
import com.yn.xr.user.mode.UserLoginLog;
import com.yn.xr.user.mode.UserRegister;

/**
 * @description:RMI接口实现类
 * @fileName:UserRegisterRmiServiceImpl.java
 * @createTime:2015年1月24日 下午18:19:09
 * @author:陈权福
 * @version 1.0.0
 */
@Service("qbUserRegisterRmiService")
public class UserRegisterRmiServiceImpl implements UserRegisterRmiService {

	@Resource
	private UserRegisterService userRegisterService;

	@Resource
	private UserLoginLogService userLoginLogService;

	private static final Logger log = LoggerFactory
			.getLogger(UserRegisterRmiServiceImpl.class);

	/**
	 */
	public UserRegister findUserRegisterByAccAndPwd(String accName, String pwd) throws BaseException {
		log.info("UserRegisterRmiServiceImpl's findUserRegisterByAccAndPwd【中间件登录】进入,惠信号为:" + accName + "密码为:" + pwd);
		String acc = accName.trim();
		UserRegister register = null;
		try {
			register = userRegisterService.queryUserRegisterByAccNameAndPass( acc, pwd);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("UserRegisterRmiServiceImpl's login【中间件登录】捕获登陆异常 ：", e);
			throw new UserLoginException("登录失败");// 用户在本地被锁定，登录失败
		}
		if (register == null) {
			throw new UserLoginException("当前用户不存在");// 用户在本地被锁定，登录失败
		}
		// 记录登入日志
		saveUserLoginLog(register,null,null);
		return register;
	}
	
	
	/**
	 * @Description: 记录登入日志
	 * @author wangpinwen
	 * @date 2015年8月25日 上午11:59:21 
	 * @version V1.0.0
	 * @param userRegister
	 * @param mac   登陆ip/登陆mac地址
	 */
    private void saveUserLoginLog(UserRegister userRegister, String mac , String ip ) {
        try {
        	 if ( userRegister !=  null ) {
	   			 UserLoginLog userLoginLog = new UserLoginLog();
	   			 userLoginLog.setUserId(userRegister.getUserId());
	   			 userLoginLog.setAccName(userRegister.getAccName());
	   			 userLoginLog.setLoginTime(userRegister.getLogiTempTime());
	   			 userLoginLog.setIp(ip);	//ServletActionContext.getRequest().getRemoteAddr()
	   			 userLoginLog.setMacAddress(mac);
	   			 userLoginLogService.save(userLoginLog);
        	 }
   		} catch (Exception e) {
   			log.error("记录登陆日志失败",e);
   		}
    }
    
    
    /**
     * @Description: 根据用户id获取用户对象
     * @author wangpinwen
     * @date 2015年8月25日 下午12:38:34 
     * @version V1.0.0
     * @param userId
     * @return
     * @throws BaseException
     */
    public UserRegister getUserRegisterByUserId( Long userId ) throws BaseException{
    	return userRegisterService.findById(userId);
    }
}
